package com.github.ghsea.scheduler.zkclient;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EphemeralNodeRebuilder implements ConnectionStateListener {

	private ZkClient client;
	private String path;
	private Object data;

	private Logger log = LoggerFactory.getLogger(EphemeralNodeRebuilder.class);

	public EphemeralNodeRebuilder(final ZkClient client, final String path, final Object data) {
		this.client = client;
		this.path = path;
		this.data = data;
	}

	@Override
	public void stateChanged(CuratorFramework curator, ConnectionState newState) {
		if (newState == ConnectionState.RECONNECTED) {
			try {
				if (!client.exist(path)) {
					client.createEphemeral(path, data);
					log.debug("rebuild the ephemeral node sucessfully:{}", this.path);
				}
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		}
	}

}
